package com.qk.management.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.aliyun.oss.model.OSSObjectSummary;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qk.common.util.AliYunOSSOperators;
import com.qk.entity.User;
import com.qk.management.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:gzc
 * @Date: 2025/10/11 17:42
 * @Description:
 */
@Component
@Slf4j
public class AliYunOssTask {

    @Autowired
    private  AliYunOSSOperators aliYunOSSOperators;
    @Autowired
    private UserMapper userMapper;
    @Scheduled(cron = "0 0 1 * * ?")// 每天凌晨一点执行
    public void cleanRedundantFiles() throws Exception {
        log.info("定时任务开始清理多余文件");
        log.info("当前时间：{}", LocalDateTime.now());
        LocalDateTime yesterday = LocalDateTime.now().minusDays(1);
        String yesterdayPath = LocalDateTimeUtil.format(yesterday, "yyyy/MM/dd");
        String yesterdayDb = LocalDateTimeUtil.format(yesterday, "yyyy-MM-dd");
        List<String> allImages = aliYunOSSOperators.listFiles(yesterdayPath).stream().map(OSSObjectSummary::getKey).collect(Collectors.toList());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(User::getCreateTime, yesterdayDb);
        List<String> userImages = userMapper.selectList(queryWrapper).stream()
                .map(user -> {
                    int index = user.getImage().indexOf("com/");
                    return user.getImage().substring(index + 4);
                }).collect(Collectors.toList());
        List<String> deleteImages = allImages.stream()
                .filter(image -> !userImages.contains(image))
                .collect(Collectors.toList());
        log.info("待删除文件：{}", deleteImages);
        if (CollectionUtil.isNotEmpty(deleteImages)){
            aliYunOSSOperators.batchDeleteFiles(deleteImages);
        }
    }
}
